﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using RenRenClient;
using Microsoft.Phone.Shell;

namespace RenRenWP
{
    public partial class MainPage : PhoneApplicationPage
    {
        RennClient client;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            //DataContext = App.ViewModel;

            ApplicationBarMenuItem logoutItem = new ApplicationBarMenuItem("注销");
            logoutItem.Click += new EventHandler(logoutItem_Click);
            ApplicationBarIconButton btnRefresh = new ApplicationBarIconButton(new Uri("/Images/Refresh.png", UriKind.Relative));
            btnRefresh.Text = "刷新";
            btnRefresh.Click += new EventHandler(btnRefresh_Click);

            ApplicationBar = new ApplicationBar();
            ApplicationBar.IsMenuEnabled = true;
            ApplicationBar.IsVisible = true;
            ApplicationBar.Opacity = 1.0;

            ApplicationBar.MenuItems.Add(logoutItem);
            ApplicationBar.Buttons.Add(btnRefresh);

            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadData();
        }

        void logoutItem_Click(object sender, EventArgs e)
        {
            client.token.EraseHistory();
            NavigationService.Navigate(new Uri("/Login.xaml", UriKind.Relative));
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }

            client = new RennClient(Login.oauth);

            LoadData();

        }

        private void LoadData()
        {
            client.BeginGetFriends(delegate(List<RennFriend> ar)
            {
                var friends = ar;
                UIThread.Invoke(() =>
                {
                    FriendList.ItemsSource = friends;
                });
            });

            client.BeginGetFeeds("10,20,21,30,32,33,34,40,50,51,52", delegate(List<RennFeed> ar)
            {
                var feeds = ar;
                UIThread.Invoke(() =>
                {
                    FeedList.ItemsSource = feeds;
                });
            });
        }

        private void PanoramaItem_GotFocus(object sender, RoutedEventArgs e)
        {

        }
    }
}